<template>
  <!-- 注册页面的整体盒子 -->
  <div class="login-container">
    <!-- 注册的盒子 -->
    <div class="login-box">
      <!-- 标题的盒子 -->
    <div class="title-box"></div>
      <!-- 注册的表单区域 -->
     <el-form :model="loginForm" :rules="loginRules" ref="loginRef"  class="demo-loginForm">
    <el-form-item  prop="username">
    <el-input v-model="loginForm.username" placeholder="用户名" prefix-icon="el-icon-user"></el-input> 
   </el-form-item>
       <!--输入密码后自动登录方法 @keydown.enter.native="login" -->
    <el-form-item  prop="password">
    <el-input v-model="loginForm.password" type="password" placeholder="密码" prefix-icon="el-icon-lock" @keydown.enter.native="login"></el-input> 
   </el-form-item>

    <el-form-item>
   <el-button type="primary" round class="btn-login" @click="login">登录</el-button>
      <el-link type="primary" @click="$router.push('/reg')">去注册</el-link>
  </el-form-item>
     </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data() {
    return {
      // 表单数据对象
     loginForm:{
      username:'',
      password:'' 
     },
    //  表单数据校验
     loginRules:{
        username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            {patter:/^[a-zA-Z0-9]{1,10}$/,message:'用户名长度必须要以数字或字母组成1~10位',trigger: 'blur' }
         ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { pattern: /^\S{6,15}$/, message: '密码必须是6-15的非空字符', trigger: 'blur' }
          ],
     }
    };
  },
  methods: {
    login(){
       // 1.对表单数据进行兜底校验,获取el-form组件对象 调用组件对象方法validate
      //  获取DOM元素对象this.$refs.ref的属性值
       this.$refs.loginRef.validate(async valid =>{
        //  console.log(volid);
        //  2.判断valid是否为false
        if(!valid)retuen
        // 3.表达里面的数据合法,发送ajax请求
        const {data:res} = await this.$http.post('/api/login',this.loginForm)
        // console.log(res);
        // 4.判断登录失败
        if(res.code !== 0)return this.$message.error(res.message)
         //  5.登陆成功
      this.$message.success(res.message)
      // console.log(res);
      // 将服务器响应回来的token保存到vuex中
      // 触发vuex里面mutations里面的函数
      this.$store.commit('updateToken', res.token)
      this.$router.push('/')
       })
     
    }
  }
}
</script>

<style lang="less" scoped>
.login-container {
  background: url('../../assets/images/login_bg.jpg') center;
  background-size: cover;
  height: 100%;

  .login-box {
    width: 400px;
    height: 335px;
    background-color: #fff;
    border-radius: 3px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    padding: 0 30px;
    box-sizing: border-box;

    .title-box {
      height: 60px;
      background: url('../../assets/images/login_title.png') center no-repeat;
    }

    .btn-login {
      width: 100%;
    }
  }
}

</style>
